<template>
  <div class="flex flex-wrap gap-4" >
    <el-breadcrumb style="margin-bottom: 20px;">
    <el-breadcrumb-item><b>数据筛选</b></el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索信息 -->
    <el-card style="width: 1800px" shadow="always">
      <el-button type="success" plain @click="dialogFormVisible = true" style="margin-bottom: 25px;">高级搜索</el-button>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="销售单号">
      <el-input v-model="formInline.Sell__Number" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="产品编号">
      <el-input v-model="formInline.Product_Number" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="产品名称">
      <el-input v-model="formInline.Product_Name" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <!-- <el-form-item label="订单状态">
      <el-select
      v-model="formInline.region"
      placeholder="请选择"
      clearable
      >
      <el-option label="Zone one" value="shanghai" />
      <el-option label="Zone two" value="beijing" />
      </el-select>
      </el-form-item> -->

      <el-form-item>
      <el-button type="primary" @click="SellShow()">搜索</el-button>
      <el-button  @click="onSubmit">重置</el-button>
      </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 信息的显示 -->
  <div class="flex flex-wrap gap-4" style="margin-top: 20px;">
    <el-button type="success" @click="handleClick">+新增</el-button>
    <el-button type="warning" @click="handleClick">编辑</el-button>
    <el-button type="danger" @click="delall()">批量删除</el-button>
    <el-button type="info" @click="SellShow()">刷新</el-button>
    <el-button type="primary" >导出</el-button>
    
    <!-- 复选框操作按钮 -->
    <el-button size="small" @click="clearSelection">清空选择</el-button>
    <el-button size="small" @click="toggleSelection">全选/反选</el-button>
    <el-button size="small" @click="showSelectedInfo">查看选中</el-button>
    <el-card style="width: 1800px" shadow="always">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="tableRef"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sell__Number" label="订单号" width="80" />
        <el-table-column prop="product_Name" label="产品名称" width="80" />
        <el-table-column prop="product_Number" label="产品编号" width="80" />
        <el-table-column prop="specifications" label="产品规格" width="80" />
        <el-table-column prop="storage_Unit" label="单位" width="80" />
        <el-table-column prop="price" label="单价" width="80" />
        <el-table-column prop="sProduct__Num" label="数量" width="80" />
        <!-- <el-table-column prop="date" label="总额" width="80" /> -->
        <!-- <el-table-column prop="date" label="出库数" width="80" />
        <el-table-column prop="date" label="客户单号" width="80" /> -->
        <el-table-column prop="customer_Number" label="客户编号" width="80" />
                 <el-table-column prop="customer_Name" label="客户名" width="80" />
         <el-table-column label="订单总额" width="80">
           <template #default="scope">
             {{ calculateTotalAmount(scope.row) }}
           </template>
         </el-table-column>
        <el-table-column prop="notes" label="状态" width="80" />
         <el-table-column prop="recorded" label="是否入账" width="80" /> 
        <el-table-column label="退货" width="80">
          <template #default="scope">
            {{ scope.row.sell_Return ? '否' : '是' }}
          </template>
        </el-table-column>
        <el-table-column prop="return_Number" label="退货数" width="80" /> 
        <el-table-column prop="createTime" label="创建时间" width="80" />
        <el-table-column  label="操作"  width="380">
          <template v-slot="scoped">
            <el-button type="info" @click="viewDetails(scoped.row)">查看</el-button>
            <el-button 
              v-if="scoped.row.notes !== '全部入库'" 
              type="success"
            >入库</el-button>
            <el-button type="danger" @click="open(scoped.row.id || 0)">删除</el-button>
            <el-button type="warning">退货</el-button>
            <el-button type="primary">入账</el-button>
          </template>
        </el-table-column>
        </el-table>
    </el-card>

          <!-- 分页数据的显示 -->
      <el-pagination
      v-model:current-page="data.PageIndex"
      v-model:page-size="data.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="data.totaCount"
      />
  </div>

  <!-- 高级搜索弹出框 -->
  <el-dialog v-model="dialogFormVisible" title="高级搜索" width="500">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="销售单号">
    <el-input v-model="formInline.Sell__Number"  clearable />
    </el-form-item>

    <el-form-item label="产品编码">
    <el-input v-model="formInline.Product_Number"  clearable />
    </el-form-item>

    <el-form-item label="产品名称">
    <el-input v-model="formInline.Product_Name"  clearable />
    </el-form-item>

    <el-form-item label="客户编号">
    <el-input v-model="formInline.Customer__Number" clearable />
    </el-form-item>

    <el-form-item label="客户名称">
    <el-input v-model="formInline.Customer_Name"  clearable />
    </el-form-item>


    <!-- <el-form-item label="起始时间">
    <el-date-picker
    v-model="formInline.date"
    type="date"
    placeholder="起始时间"
    clearable
    />
    </el-form-item> -->
    <el-form-item>
    <el-button type="primary" @click="SellShow()">查询</el-button>
    </el-form-item>
    </el-form>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          Confirm
        </el-button>
      </div>
    </template> -->
     </el-dialog>

   <!-- 销售订单详情弹出框 -->
   <el-dialog v-model="detailDialogVisible" title="销售订单明细" width="1200px" :before-close="handleDetailClose">
     <div v-if="currentDetail">
       <!-- 订单基本信息 -->
       <el-card class="detail-card" shadow="never">
         <template #header>
           <div class="card-header">
             <span>订单基本信息</span>
           </div>
         </template>
         <el-row :gutter="20">
           <el-col :span="8">
             <div class="detail-item">
               <label>订单号：</label>
               <span>{{ currentDetail.sell__Number || '-' }}</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>单据类型：</label>
               <span>实际订单</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>单据状态：</label>
               <span>{{ getStatusText(currentDetail.sell_State) }}</span>
             </div>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="8">
             <div class="detail-item">
               <label>制单人：</label>
               <span>{{ currentDetail.createUse || '系统' }}</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>制单日期：</label>
               <span>{{ formatDate(currentDetail.createTime) }}</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>发货日期：</label>
               <span>{{ formatDate(currentDetail.createTime) }}</span>
             </div>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="8">
             <div class="detail-item">
               <label>客户编号：</label>
               <span>{{ currentDetail.customer__Number || '-' }}</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>客户名称：</label>
               <span>{{ currentDetail.customer_Name || '-' }}</span>
             </div>
           </el-col>
           <el-col :span="8">
             <div class="detail-item">
               <label>联系人：</label>
               <span>{{ currentDetail.customer_Name || '-' }}</span>
             </div>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="8">
             <div class="detail-item">
               <label>电话：</label>
               <span>{{ currentDetail.customerPhone || '-' }}</span>
             </div>
           </el-col>
           <el-col :span="16">
             <div class="detail-item">
               <label>备注：</label>
               <span>{{ currentDetail.remarks || '-' }}</span>
             </div>
           </el-col>
         </el-row>
       </el-card>

       <!-- 产品列表 -->
       <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
         <template #header>
           <div class="card-header">
             <span>产品信息</span>
           </div>
         </template>
         <el-table :data="productList" border style="width: 100%">
           <el-table-column prop="product_Number" label="产品编码" width="120" />
           <el-table-column prop="product_Name" label="产品名称" width="150" />
           <el-table-column prop="specifications" label="规格" width="100" />
           <el-table-column prop="storage_Unit" label="单位" width="80" />
           <el-table-column prop="sProduct__Num" label="数量" width="100" />
           <el-table-column prop="price" label="单价" width="100">
             <template #default="scope">
               ¥{{ scope.row.price || 0 }}
             </template>
           </el-table-column>
           <el-table-column label="总额" width="120">
             <template #default="scope">
               ¥{{ calculateTotal(scope.row) }}
             </template>
           </el-table-column>
         </el-table>
       </el-card>
     </div>

     <template #footer>
       <div class="dialog-footer">
         <el-button @click="detailDialogVisible = false">关闭</el-button>
         <el-button type="primary" @click="confirmDetail">确认</el-button>
       </div>
     </template>
   </el-dialog>
 </template>

<script lang="ts" setup>
import { reactive, ref, onMounted,watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { BusinessRed } from '@/http/axiosHelper'
import { BusinessWrite } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型接口
interface SellData {
  id?: number
  sell__Number?: string
  product_Name?: string
  product_Number?: string
  specifications?: string
  storage_Unit?: string
  price?: number
  sProduct__Num?: number
  customer__Number?: string
  customer_Name?: string
  sell_State?: string
  sell_Return?: boolean
  return_Number?: string
  createTime?: string
  createUse?: string
  customerPhone?: string
  remarks?: string
  notes?: string
  recorded?: boolean
}
const router = useRouter();
const route = useRoute();

//销售信息新增页面
const handleClick = () => {
  router.push({name:'SellAddShow'})
}

//生命周期钩子函数
onMounted(()=>{
  SellShow()
})

//数据信息的显示
const tableData = ref<SellData[]>([])

//表格复选框相关
const tableRef = ref<any>()
const selectedRows = ref<SellData[]>([])
const selectedIds = ref<number[]>([])

//数据信息的显示
const data = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Purchase__Supplier: string
}>({
    PageIndex: 1,
    PageSize: 15,
    totaCount:0,
    Purchase_Number:'',
    Product_Number:'',
    Product_Name:'',
    Purchase__Supplier:''
})

const SellShow = ()=>{
   BusinessRed.get("api/Purchase/SellShow", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
            Sell__Number:formInline.Sell__Number,
            Product_Number:formInline.Product_Number,
            Product_Name:formInline.Product_Name,
            Customer_Name:formInline.Customer_Name,
            Customer__Number:formInline.Customer__Number
        }
    })
        .then((res: any) => {
            tableData.value = res.data.data;
            data.value.totaCount = res.data.totaCount
        })
        .catch((err: any) => {
            ElMessage.error("查询失败")
            console.error(err)
        })
}

//分页监听事件
watch([() => data.value.PageIndex, () => data.value.PageSize], () => {
  SellShow();
}, { deep: true })


//高级搜索弹出框
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

// 详情弹出框相关
const detailDialogVisible = ref(false)
const currentDetail = ref<SellData | null>(null)
const productList = ref<SellData[]>([])

//条件查询
const formInline = reactive<{
    Sell__Number: string
    Product_Number: string
    Product_Name: string
    Customer_Name: string
    Customer__Number: string
}>({
Sell__Number:'',
Product_Number:'',
Product_Name:'',
Customer_Name:'',
Customer__Number:''
})








// 单个删除
const open = (id: number) => {
  ElMessageBox.confirm(
    '该操作将删除该数据,确定要删除吗？',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      console.log(id)
      BusinessWrite.post('/api/Purchase/DelSell', { id: id })
        .then((res: any) => {
          if (res.data.code == 200) {
            ElMessage.success("删除成功");
            SellShow();
          } else {
            ElMessage.error("删除失败");
          }
        })
        .catch((err: any) => {
          ElMessage.error("删除失败");
          console.error(err);
        })
    })
    .catch(() => {
      ElMessage.info('删除取消')
    })
}


//处理复选框选择变化
const handleSelectionChange = (selection: SellData[]) => {
  selectedRows.value = selection;
  selectedIds.value = selection.map(row => row.id || 0).filter(id => id !== 0);
  
  console.log('选中的行数据:', selectedRows.value);
  console.log('选中的ID列表:', selectedIds.value);
  
  // 显示选中的信息
  if (selectedIds.value.length > 0) {
    ElMessage.info(`已选中 ${selectedIds.value.length} 条记录，ID: ${selectedIds.value.join(', ')}`);
  }
}

//获取选中的ID列表
const getSelectedIds = () => {
  return selectedIds.value;
}

//清空选择
const clearSelection = () => {
  if (tableRef.value) {
    (tableRef.value as any).clearSelection();
  }
  selectedIds.value = [];
  selectedRows.value = [];
  console.log('已清空所有选择');
}

//切换全选状态
const toggleSelection = () => {
  if (tableRef.value) {
    (tableRef.value as any).toggleAllSelection();
  }
}

//显示选中信息
const showSelectedInfo = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.info('当前没有选中任何记录');
    return;
  }
  
  const info = selectedRows.value.map(row => 
    `ID: ${row.id}, 订单号: ${row.sell__Number}, 产品: ${row.product_Name}`
  ).join('\n');
  
  ElMessageBox.alert(
    info,
    `选中的 ${selectedIds.value.length} 条记录详情`,
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  );
}

const onSubmit = () => {
  // 重置表单
  formInline.Sell__Number = ''
  formInline.Product_Number = ''
  formInline.Product_Name = ''
  formInline.Customer_Name = ''
  formInline.Customer__Number = ''
  // 重新加载数据
  SellShow()
}

// 查看详情
const viewDetails = (row: SellData) => {
  currentDetail.value = row
  // 将当前行数据作为产品列表显示（实际项目中可能需要调用API获取详细产品信息）
  productList.value = [row]
  detailDialogVisible.value = true
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error: any) {
    return dateString
  }
}

// 获取状态文本
const getStatusText = (status: string | undefined) => {
  if (!status) return '未知状态'
  switch (status) {
    case '0':
      return '创建订单'
    case '1':
      return '已确认'
    case '2':
      return '已发货'
    case '3':
      return '已完成'
    default:
      return '未知状态'
  }
}

// 计算总额
const calculateTotal = (row: SellData) => {
  const price = parseFloat(row.price?.toString() || '0')
  const quantity = parseFloat(row.sProduct__Num?.toString() || '0')
  return (price * quantity).toFixed(2)
}

// 处理详情弹窗关闭
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentDetail.value = null
  productList.value = []
}

// 确认详情
const confirmDetail = () => {
  ElMessage.success('操作成功')
  detailDialogVisible.value = false
}




//列表批量删除方法
const delall = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条记录吗？\nID: ${selectedIds.value.join(', ')}`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      console.log('准备删除的ID数组:', selectedIds.value);
      // 将选中的ID数组传递给API
      BusinessWrite.post('/api/Purchase/DellAllSell', {
        Id: selectedIds.value  // 传递ID数组
      })
        .then((res: any) => {
          if (res.data.code == 200) {
            ElMessage.success(`成功删除 ${selectedIds.value.length} 条记录`);
            // 清空选择状态
            selectedIds.value = [];
            selectedRows.value = [];
            clearSelection();
            // 重新加载数据
            SellShow();
          } else {
            ElMessage.error("删除失败：" + (res.data.message || '未知错误'));
          }
        })
        .catch((err: any) => {
          ElMessage.error("删除失败");
          console.error('删除API调用失败:', err);
        })
    })
    .catch(() => {
      ElMessage.info('已取消批量删除');
    })
}










</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
b{
  color: black;
}

/* 详情弹窗样式 */
.detail-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.detail-item {
  margin-bottom: 15px;
  line-height: 1.6;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
  display: inline-block;
}

.detail-item span {
  color: #303133;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>